package com.wshl.cloudservice.activities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wshl.cloudservice.CloudServiceApplication;
import com.wshl.cloudservice.Constants;
import com.wshl.cloudservice.R;
import com.wshl.cloudservice.ui.widget.LoadingDialog;
import com.wshl.cloudservice.utils.RtcUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import io.agora.rtc.RtcEngine;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.LocalInvitation;
import io.agora.rtm.RemoteInvitation;
import io.agora.rtm.ResultCallback;

import io.agora.rtm.RtmMessage;

/**
 * 排队等待页面
 */
public class WaitActivity extends BaseCallActivity implements View.OnClickListener, ResultCallback<Void> {


    private static final String TAG = "openduo";

    private TextView tvCancel;
    private TextView tvCall;

    private boolean isInvitation = false;
    private Timer timer;

    private TextView tvWei;
    private TextView tvWaitTime;
    private boolean isGotoVideo = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wait);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)//设置状态栏颜色为白色
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        //init();
        checkPermissions();
        initView();


        final Timer timer1 = new Timer();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!NetworkUtils.isConnected()) {
                    LogUtils.i("无网络连接，无法获取账号信息");
                    ToastUtils.showLong("您的网络出错了");
                    return;
                }
                timer1.cancel();
                //获取账号
                getAccount();
            }
        }, 0, 1000 * 3);


        timer = new Timer();

    /*    //获取账号
        getAccount();
        //定时器，5秒后调用一次，之后每隔三秒调用一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                getWaitState();
            }
        }, 5000, 1000 * 3);
*/


    }


    private boolean isRtmLoginSuccess = false;

    private void rtmLogin() {

//        global().setmUserId("2021");
//        global().setPeerId("6060");
//        global().setmNickname("用户:");
//        global().setPeerNIckname("客服小娜:");

        rtmClient().login(null, global().getmUserId(), new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "WaitActivity==== rtm client login success");
                LogUtils.i("rtm client login success");
                //  ToastUtils.showLong("rtm登陆成功，uid:" + global().getmUserId());
                isRtmLoginSuccess = true;
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                isRtmLoginSuccess = false;
                // ToastUtils.showLong("rtm登陆失败，uid:" + global().getmUserId());
                LogUtils.i("rtm client login failed:" + errorInfo.getErrorDescription());
                Log.i(TAG, "WaitActivity====  rtm client login failed:" + errorInfo.getErrorDescription());

            }
        });
    }

    private void initView() {

        tvCall = findViewById(R.id.tv_call);
        tvCancel = findViewById(R.id.tv_cancel_wait);
        tvWei = findViewById(R.id.tv_wei);
        tvWaitTime = findViewById(R.id.tv_wait_time);
        tvCancel.setOnClickListener(this);
        tvCall.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel_wait://退出
                dialogUtils.showCustomdialog(this, "正在排队中，是否要取消？", false, true, "提示", "取消", "确定");

                break;
            case R.id.tv_call://模拟呼叫
             /*   if (isRtmLoginSuccess) {
                    rtmLogin();
                }

                final String peer = global().getPeerId();
                Set<String> peerSet = new HashSet<>();
                peerSet.add(peer);
                //判断远端是否登录IM
                rtmClient().queryPeersOnlineStatus(peerSet,
                        new ResultCallback<Map<String, Boolean>>() {
                            @Override
                            public void onSuccess(Map<String, Boolean> statusMap) {
                                Boolean bOnline = statusMap.get(peer);

                                if (bOnline != null && bOnline) {
                                    final String channel = RtcUtils.channelName(global().getmUserId(), peer);
                                    Log.i("openduo", "channelname: " + channel);

                                    startCall(channel, peer);

                                    //先跳转到CallActivity,有一个呼叫过程
                                    // gotoCallingInterface(peer, channel, Constants.ROLE_CALLER);
                                    //直接去视频页面
                                    //  gotoVideoActivity(channel,peer);
                                    // WaitActivity.this.finish();


                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(WaitActivity.this,
                                                    R.string.peer_not_online,
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }

                            @Override
                            public void onFailure(ErrorInfo errorInfo) {
                                Log.i(TAG, "onFailure: " + errorInfo.getErrorDescription());
                            }
                        });*/


                break;
        }
    }

    private void startCall(final String channel, final String peer) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                LoadingDialog.showLoading(WaitActivity.this, "正在连线中..");
                //远端在线，直接发起呼叫邀请
                inviteCall(peer, channel);

            }
        });
    }


    /**
     * 发起呼叫邀请
     *
     * @param peerUid
     * @param channel
     */
    protected void inviteCall(final String peerUid, final String channel) {
        LocalInvitation invitation = rtmCallManager().createLocalInvitation(peerUid);
        invitation.setContent(channel);
        rtmCallManager().sendLocalInvitation(invitation, this);
        global().setLocalInvitation(invitation);
        //正在呼叫中
        isInvitation = true;
    }


    private void checkPermissions() {
        XXPermissions.with(this)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE, Permission.RECORD_AUDIO)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
    }


    private void destroyEngine() {
        //RtcEngine.destroy();

        rtmClient().logout(new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "rtm client logout success");
                LogUtils.i("rtm client logout success");
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                Log.i(TAG, "rtm client logout failed:" + errorInfo.getErrorDescription());
                LogUtils.i("rtm client logout failed" + errorInfo.getErrorDescription());
            }
        });
    }


    /**
     * 远端主播接受了呼叫邀请之后，跳转视频页面
     *
     * @param channel
     * @param peer
     */
    public void gotoVideoActivity(String channel, String peer) {
        Intent intent = new Intent(this, VideoActivity.class);
        intent.putExtra(Constants.KEY_CALLING_CHANNEL, channel);
        intent.putExtra(Constants.KEY_CALLING_PEER, peer);
        startActivity(intent);
    }


    @Override
    public void onJoinChannelSuccess(String channel, int uid, int elapsed) {

    }

    @Override
    public void onUserJoined(int uid, int elapsed) {

    }

    @Override
    public void onUserOffline(int uid, int reason) {

    }

    @Override
    public void onConnectionStateChanged(int status, int reason) {

    }

    @Override
    public void onPeersOnlineStatusChanged(Map<String, Integer> map) {

    }

    @Override
    public void onLocalInvitationReceived(LocalInvitation localInvitation) {

        Log.i(TAG, "onLocalInvitationReceived: 远端收到了呼叫邀请");
    }

    @Override
    public void onLocalInvitationAccepted(LocalInvitation localInvitation, String response) {
        Log.i(TAG, "onLocalInvitationReceived: 远端接受了呼叫邀请:" + localInvitation.getContent() + ";" + localInvitation.getCalleeId());
        isInvitation = false;
        isGotoVideo = true;
        LoadingDialog.hideLoading();
        gotoVideoActivity(localInvitation.getContent(), localInvitation.getCalleeId());
    }

    @Override
    public void onLocalInvitationRefused(LocalInvitation localInvitation, String response) {

        Log.i(TAG, "onLocalInvitationReceived: 远端拒绝了呼叫邀请:" + localInvitation.getContent() + ";" + localInvitation.getCalleeId());
        ToastUtils.showShort(" 远端客服拒绝了呼叫邀请");
        isInvitation = false;
        LoadingDialog.hideLoading();

    }

    @Override
    public void onLocalInvitationCanceled(LocalInvitation localInvitation) {
        Log.i(TAG, "onLocalInvitationReceived: 取消了呼叫:" + localInvitation.getContent() + ";" + localInvitation.getCalleeId());
        isInvitation = false;
        LoadingDialog.hideLoading();
    }

    @Override
    public void onLocalInvitationFailure(LocalInvitation localInvitation, int errorCode) {
        Log.i(TAG, "onLocalInvitationReceived: 呼叫失败:" + localInvitation.getContent() + ";" + localInvitation.getCalleeId());
        isInvitation = false;
        LoadingDialog.hideLoading();

    }


    @Override
    public void onRemoteInvitationReceived(RemoteInvitation remoteInvitation) {
        Log.i(TAG, "onRemoteInvitationReceived: 收到远端呼叫：" + remoteInvitation.getCallerId());
    }

    @Override
    public void onRemoteInvitationAccepted(RemoteInvitation remoteInvitation) {
        Log.i(TAG, "onRemoteInvitationReceived: 接受远端呼叫邀请：" + remoteInvitation.getCallerId());
    }

    @Override
    public void onRemoteInvitationRefused(RemoteInvitation remoteInvitation) {

    }

    @Override
    public void onRemoteInvitationCanceled(RemoteInvitation remoteInvitation) {

    }

    @Override
    public void onRemoteInvitationFailure(RemoteInvitation remoteInvitation, int errorCode) {

    }

    @Override
    public void onRemoteDecoding(int uid, int state) {

    }

    @Override
    public void onMessAgeReceive(RtmMessage rtmMessage, String senduid) {

    }

    @Override
    public void onSuccess(Void aVoid) {
        Log.i(TAG, "onSuccess: 发起呼叫成功");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        Log.i(TAG, "onFailure: 发起呼叫失败：" + errorInfo.getErrorDescription());
        isInvitation = false;
        LoadingDialog.hideLoading();
    }


    @Override
    public void onBackPressed() {
        String content = "正在排队中，是否要离开？";
        if (isInvitation) {
            content = "正在连线中，是否要离开？";
//            if (progressDialog != null && progressDialog.isShowing()) {
//                progressDialog.dismiss();
//            }
        }
        dialogUtils.showCustomdialog(this, content, false, true, "提示", "取消", "确定");
    }

    @Override
    public void setConfirm() {
        super.setConfirm();

        if (isInvitation) {
            //如果正在呼叫中，则先停止呼叫
            cancelLocalInvitation();
        }
        //然后停止排队
        cacelWait();


    }

    @Override
    public void setCancel() {
        super.setCancel();
    }

    @Override
    public void finish() {
        super.finish();
        //  destroyEngine();
//        if (isInvitation) {
//            cancelLocalInvitation();
//        }

    }


    @Override
    public void onStop() {
        super.onStop();
        LogUtils.i("onStop");

        if (timer != null) {
            timer.cancel();
            timer = null;
        }

       /* if (isInvitation) {
            //如果正在呼叫中，则停止呼叫
            cancelLocalInvitation();
            finish();
        } else {
            //如果正在排队中，停止排队
            cacelWait();
        }*/

        if (isInvitation) {
            //如果正在呼叫中，则先停止呼叫
            cancelLocalInvitation();
        }

        //已经取消过了，就不用再取消
        if (isCancel) {
            return;
        }

        //如果是去呼叫页面了,则不能退出登录
//        if (isGotoVideo) {
//            finish();
//            return;
//        }
        //然后停止排队
        cacelWait();


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.i("ondestroy");

        if (timer != null) {
            timer.cancel();
            timer = null;
        }


    }


    private void getAccount() {
        LogUtils.i(Thread.currentThread().getName());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LoadingDialog.showLoading(WaitActivity.this, "加载中..");
                if (!NetworkUtils.isConnected()) {
                    LoadingDialog.hideLoading();
                    ToastUtils.showLong("您的网络出错了");
                    return;
                }
            }
        });


        OkGo.<String>post(CloudServiceApplication.JOIN)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("join:" + response.body());
                        LoadingDialog.hideLoading();
                        // ToastUtils.showLong(response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case "200":
                                        if (jsonObject.has("data")) {
                                            String data = jsonObject.getString("data");
                                            JSONObject datajson = new JSONObject(data);

                                            String token = datajson.getString("remember_token");
                                            String uid = datajson.getString("id");
                                            String name = datajson.getString("name");
                                            String channelname = datajson.getString("room_id");
                                            String service_name = datajson.getString("service_name");
                                            String service_avatar = datajson.getString("service_avatar");

                                            //保存相关属性
                                            global().setToken(token);
                                            global().setmUserId(uid);
                                            global().setmNickname(name);
                                            global().setChannelName(channelname);
                                            global().setPeerNIckname(service_name);
                                            global().setPeerAvatar(service_avatar);

                                            LogUtils.i("保存token:" + token + ";" + uid);

                                            rtmLogin();

                                            String total_user = datajson.getString("total_user");
                                            String rownum = datajson.getString("rownum");
                                            setWaitInfo(total_user, rownum);

                                            String service_id = datajson.getString("service_id");
                                            if (TextUtils.isEmpty(service_id) || service_id.equals("0")) {
                                                //等于0表示没有排到自己，然后每隔3秒循环一次
                                                timer.schedule(new TimerTask() {
                                                    @Override
                                                    public void run() {
                                                        getWaitState();
                                                    }
                                                }, 2000, 1000 * 3);
                                                return;
                                            }

                                            //如果客服id部位0，则直接发起呼叫
                                            LogUtils.i("客服id:" + service_id);
                                            global().setPeerId(service_id);

                                            //不需要再轮询了，取消定时器
                                            if (timer != null) {
                                                timer.cancel();
                                                timer = null;
                                            }
                                            //发起呼叫
                                            startCall(channelname, service_id);

                                        }
                                        break;
                                    default:
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showLong(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LoadingDialog.hideLoading();
                        Log.i(TAG, "join: " + response.body());

                    }
                });


    }

    /**
     * 显示等待信息
     *
     * @param total_user
     * @param rownum
     */
    private void setWaitInfo(final String total_user, final String rownum) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                String content = "第 " + rownum + " 位/共 " + total_user + " 位";
                SpannableString ss = new SpannableString(content);
                ss.setSpan(new AbsoluteSizeSpan(ConvertUtils.dp2px(28)), 2, 2 + rownum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new AbsoluteSizeSpan(ConvertUtils.dp2px(28)), content.length() - 2 - total_user.length(), content.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                ss.setSpan(new ForegroundColorSpan(Color.parseColor("#50AFFF")), 2, 2 + rownum.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss.setSpan(new ForegroundColorSpan(Color.parseColor("#50AFFF")), content.length() - 2 - total_user.length(), content.length() - 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvWei.setText(ss);

                int time = Integer.valueOf(rownum) * 5;
                String content2 = "约还需 " + time + " 分钟";
                SpannableString ss2 = new SpannableString(content2);
                ss2.setSpan(new AbsoluteSizeSpan(ConvertUtils.dp2px(28)), 4, 4 + String.valueOf(time).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ss2.setSpan(new ForegroundColorSpan(Color.parseColor("#50AFFF")), 4, 4 + String.valueOf(time).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvWaitTime.setText(ss2);

            }
        });

    }

    private void getWaitState() {
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showLong("您的网络出错了");
            return;
        }
        String token = global().getToken();

        OkGo.<String>post(CloudServiceApplication.WAIT)
                .tag(this)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //  Log.i(TAG, "查询排队状态: " + response.body());
                        //  ToastUtils.showLong(response.body());
                        LogUtils.i("查询排队状态：" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case "200":

                                        if (jsonObject.has("data")) {

                                            String data = jsonObject.getString("data");
                                            JSONObject datajson = new JSONObject(data);


                                            String total_user = datajson.getString("total_user");
                                            String rownum = datajson.getString("rownum");
                                            //显示等待信息
                                            setWaitInfo(total_user, rownum);

                                            String channelname = datajson.getString("room_id");
                                            String service_name = datajson.getString("service_name");
                                            String service_avatar = datajson.getString("service_avatar");

                                            global().setChannelName(channelname);
                                            global().setPeerNIckname(service_name);
                                            global().setPeerAvatar(service_avatar);

                                            String service_id = datajson.getString("service_id");
                                            if (TextUtils.isEmpty(service_id) || service_id.equals("0")) {
                                                //等于0表示没有排到自己
                                                return;
                                            }
                                            LogUtils.i("客服id:" + service_id);
                                            global().setPeerId(service_id);

                                            if (timer != null) {
                                                timer.cancel();
                                                timer = null;
                                            }
                                            //发起呼叫
                                            startCall(channelname, service_id);

                                        }

                                        break;
                                    default:
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showLong(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.i(TAG, "查询排队状态: " + response.code());
                        LogUtils.e("查询排队状态错误：" + response.code());
                    }
                });


    }

    private boolean isCancel = false;

    private void cacelWait() {
        if (!NetworkUtils.isConnected()) {
            isCancel = true;
            if (!isGotoVideo) {
                destroyEngine();
            }
            finish();
        }

        String token = global().getToken();
        OkGo.<String>post(CloudServiceApplication.CANCEL)
                .tag(this)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LoadingDialog.hideLoading();
                        LogUtils.i("取消排队：" + response.body());


                        isCancel = true;
                        finish();

                        if (!isGotoVideo) {
                            destroyEngine();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e("取消排队：" + response.code());
                        isCancel = true;
                        if (!isGotoVideo) {
                            destroyEngine();
                        }
                        finish();
                    }
                });


    }

}
